package ck

import (
	"gitee.com/tietang/terrace-go/v2/example/moni/dao"
	"gitee.com/tietang/terrace-go/v2/lib/rpc"
	"github.com/sirupsen/logrus"
	"github.com/tietang/dbx"
	"strings"
)

var ckWebTenantDao dao.Dao = new(ClickHouseTenantRequestDao)

func init() {
	//dao.Register("tenant.RequestTenantMetrics", ckWebTenantDao)
	handler := dao.NewHandler(ckWebTenantDao)
	rpc.RegisterHandler("tenant.RequestTenantMetrics", handler)
}

type ClickHouseTenantRequestDao struct {
}

func (d *ClickHouseTenantRequestDao) Save(metrics any) {
	m := metrics.(map[string]interface{})
	metricsList := m["tenantMetricsList"].([]interface{})
	sql := sqlTenantRequestBaseSql + strings.Repeat(sqlTenantRequestValuesSql+",", len(metricsList)-1) + sqlTenantRequestValuesSql
	args := make([]interface{}, 0, 15*len(metricsList))
	for _, metric := range metricsList {
		met := metric.(map[string]interface{})
		args = append(args, m["appName"])
		args = append(args, m["tenantId"])
		args = append(args, met["uri"])
		args = append(args, m["interval"])
		args = append(args, 1000*m["seconds"].(float64))
		args = append(args, met["cost"])
		args = append(args, met["count"])
		args = append(args, met["failure40xCount"])
		args = append(args, met["failure50xCount"])
		args = append(args, met["bizErrorCount"])
		args = append(args, met["requestByteSize"])
		args = append(args, met["responseByteSize"])
		//app_name,tenantId,uri,interval,ts,cost,ct,err_40xct,err_50xct,berr_ct,req_size,res_size
	}
	Clickhouse().Tx(func(run *dbx.TxRunner) error {
		_, err := run.Exec(sql, args...)
		if err != nil {
			logrus.Error(err)
			return err
		}
		return nil
	})

}

func (d *ClickHouseTenantRequestDao) Init() {

	Clickhouse().Tx(func(run *dbx.TxRunner) error {
		_, err := run.Exec(webTenantCreateTable)
		if err != nil {
			logrus.Error(err)
			return err
		}
		return nil
	})
}

const sqlTenantRequestBaseSql = "INSERT INTO m_tenant_request( app_name,tenantId,uri,interval,ts,cost,ct,err_40xct,err_50xct,berr_ct,req_size,res_size) " +
	"values"
const sqlTenantRequestValuesSql = "(?,?,?,?,?,?,?,?,?,?,?,?)"

//cost,count,failureCount,failure40xCount,failure50xCount,errorCount,bizErrorCount, requestByteSize, responseByteSize
//"from input (' app_name String,    tenantId String, uri String, interval Int,ts UInt64, cost Int64, ct Int64, err_40xct Int64, err_50xct Int64,   berr_ct Int64, req_size Int64, res_size Int64')";

const webTenantCreateTable = "create table if not exists m_tenant_request" +
	" (" +
	" app_name String," +
	" tenantId String," +
	" shopId String," +
	" uri String," +
	" interval Int," +
	" ts UInt64," +
	" cost Int64," +
	" ct Int64," +
	" err_40xct Int64," +
	" err_50xct Int64," +
	" berr_ct Int64," +
	" req_size Int64," +
	" res_size Int64," +
	" d Date materialized toDate(round(ts / 1000))," +
	" dt DateTime materialized toDateTime(round(ts / 1000))" +
	" ) " +
	" engine = MergeTree PARTITION BY (toYYYYMM(dt), app_name)\n" +
	"        ORDER BY dt\n" +
	"        SETTINGS index_granularity = 8192;"
